package co.baiku.boot.component.core.service.impl;

import co.baiku.boot.common.exception.ApiException;
import co.baiku.boot.common.validate.Validation;
import co.baiku.boot.component.core.event.OrmWhen;
import co.baiku.boot.component.core.service.ComponentService;
import co.baiku.boot.core.orm.dao.BaseDAO;
import co.baiku.boot.core.orm.po.Po;
import co.baiku.boot.core.orm.service.impl.BaseServiceImpl;
import org.springframework.http.HttpStatus;

import java.io.Serializable;

public class ComponentServiceImpl<T extends Po<ID>, D, ID extends Serializable> extends BaseServiceImpl<T, D, ID> implements ComponentService<T, D, ID> {

    public ComponentServiceImpl(BaseDAO<T, ID> baseDAO) {
        super(baseDAO);
    }

    @Override
    public T create(T t) {
        try {
            onCreate(OrmWhen.BEFORE, t);
            Validation.assertSuccess(t);
            t = baseDAO.save(t);
            onCreate(OrmWhen.SUCCESS, t);
        } catch (Exception e) {
            onCreate(OrmWhen.FAIL, t, e);
            throw e;
        }
        return t;
    }

    @Override
    public T update(T t) {
        T before = baseDAO.getById(t.getId());
        if (before == null) {
            throw ApiException.of(HttpStatus.OK, 404, "数据不存在");
        }
        try {
            onUpdate(OrmWhen.BEFORE, before, t);
            Validation.assertSuccess(t);
            t = baseDAO.save(t);
            onUpdate(OrmWhen.SUCCESS, before, t);
        } catch (Exception e) {
            onUpdate(OrmWhen.FAIL, before, t, e);
            throw e;
        }
        return t;
    }

    @Override
    public void delete(Serializable id) {
        T t = baseDAO.getById((ID) id);
        if (t == null) {
            throw ApiException.of(HttpStatus.OK, 404, "数据不存在");
        }
        try {
            onDelete(OrmWhen.BEFORE, t);
            baseDAO.delete(t);
            onDelete(OrmWhen.SUCCESS, t);
        } catch (Exception e) {
            onDelete(OrmWhen.FAIL, t, e);
            throw e;
        }
    }
}
